package yolorpc.loadbalancer;


import yolorpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yolo
 * @Program RPC
 * @description 轮询算法实现负载均衡
 * @create 2025-05-22 17:49
 **/
public class RoundRobinLoadBalancer implements LoadBalancer{

    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if (serviceMetaInfoList.isEmpty()){
            return null;
        }
        int size = serviceMetaInfoList.size();
        // 只有一个服务器的情况，直接返回
        if (size == 1){
            return serviceMetaInfoList.get(0);
        }
        // 取模轮询实现
        int i = currentIndex.getAndIncrement() % size;
        return serviceMetaInfoList.get(i);
    }
}
